from flask import Blueprint, render_template, jsonify, request
from models.entity.dict import Dict
from models.entity.dict_category import DictCategory
import json
from utils.result import result

mod = Blueprint("core_dict_category", __name__, url_prefix="/core/dict_category", template_folder="templates",
                static_folder="static")

# 这个项目用于字典管理

@mod.route('/add/', methods=['POST'])
def add_dict_category():
    """增加字典项目分类"""
    """
    {

    "name":"1d",
    "icon":"20i",
    "code":"2656y",
    "dis_order":4,
    "description":"asdfsdfg",
    "status":2,
    "parent_id":0
    }
    """

    if request.method == 'POST':
        receive = request.data
        dict = json.loads(receive.decode("utf-8"))
        dict_category = DictCategory()
        if "id" in dict:
            dict.pop("id")
        if DictCategory.get_dict_category_by_name(dict['name']) is not None:
            return result(success=0,error_code=-1,error_msg='名称已经存在')
        if DictCategory.get_dict_category_by_code(dict['code']) is not None:
            return result(success=0, error_code=-1, error_msg='编码已经存在')
        try:
            dict_category.from_dict(dict)
        except RuntimeError as e:
            return result(success=0,error_code=-1,error_msg='格式错误')
        if dict_category.save():
            return result(success=1)
        else:
            return result(success=0,error_code=-2,error_msg='未知错误')


@mod.route('/del/', methods=['POST'])
def del_dict_category():
    """删除字典项目分类"""
    """
    {
    "id": 5
    }
    """
    if request.method == 'POST':
        receive = request.data
        dict = json.loads(receive.decode("utf-8"))
        id = dict['id']
        if not DictCategory.get_dict_category_by_id(id):
            return result(success=0,error_msg='选中项不存在',error_code=-1)
        dict_category = DictCategory.get_dict_category_by_id(id)
        # dict中如果还有关联对应的dict_category
        if len(DictCategory.get_dict_categorys_by_parent_id(dict_category.id)):
            return result(success=0,error_msg='当前字典存在下级',error_code=-2)
        if len(Dict.get_dicts_by_cate_id(id))!=0:
            return result(success=0,error_msg='当前字典存在字典项',error_code=-3)
        if dict_category.delete():
            return result(success=1)
        else:
            return result(success=0, error_msg='未知错误', error_code=-4)


@mod.route("/get_tree/", methods=["GET", "POST"])
def get_tree_json():
    """返回模块列表，这个方法可能压根就用不上,用post"""
    # 请求数据格式：无
    module_root = DictCategory().get_list_by_pid(0)  # 得到所有的根节点
    rlist = []
    for item in module_root:
        tdic = item.to_dict()
        tdic["children"] = item.get_tree_by_pid(item.id)
        rlist.append(tdic)
    return result(data=rlist)


@mod.route("/get_all/", methods=["GET", "POST"])
def get_all():
    """返回模块列表，这个方法可能压根就用不上,用post"""
    # 请求数据格式：无
    tmp = {}
    data =[]
    dict_categorys = DictCategory.get_dict_category_all() # 得到所有节点
    for item in dict_categorys:
        data.append(item.to_dict())
    return result(data=data)


@mod.route('/edit/', methods=['POST'])
def edit_dict_category():
    """增加字典项目分类"""
    """
    {
    "id":2,
    "name":"222",
    "code":"eee",
    "description":"ssss",
    "parent_id":0,
    "dis_order":3,
    "status":1
    }
    """
    if request.method == 'POST':
        receive = request.data
        dict = json.loads(receive.decode("utf-8"))
        print('dict', dict)
        # dict {'pinyin': '2', 'code': '123', 'dis_order': '21', 'id': 2, 'description': '', 'name': '123', 'dict_value': '1231', 'cate_id': 1, 'status': 'on'}
        id = dict['id']
        dict_category = DictCategory.get_dict_category_by_id(id)
        if dict['name'] != dict_category.name and DictCategory.get_dict_category_by_name(dict['name']):
            return result(success=0,error_code=-1,error_msg='名称被占用，请重新修改')
        if dict['code'] != dict_category.code and DictCategory.get_dict_category_by_code(dict['code']):
            return result(success=0,error_code=-1,error_msg='编码被占用，请重新修改')
        try:
            dict_category.from_dict(dict)
        except Exception as e:
            return result(success=0,error_code=-3,error_msg=str(e))
        if dict_category.save():
            return result(success=1)
        else:
            return result(success=0,error_msg='未知错误',error_code=-4)


@mod.route("/search/",methods=["POST"])
def search_device_type():
    """
    查询button
    """
    # request: json
    # {
    #      "query_word": "lishimin"
    # }
    if request.method == 'POST':
        receive = request.get_data()
        data = json.loads(receive.decode("utf-8"))
        tmp ={}
        extra =[]
        if 'query_word' in data:
            query_word = data['query_word']
        else:
            tmp['success'] = 0
            tmp['error_code'] = -9
            tmp['error_msg'] = "数据格式错误"
            tmp['data'] = extra
            return jsonify(tmp)
        dict_categorys = DictCategory.search(query_word)
        return result(data=dict_categorys)
